package com.beiding.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

@Configuration
public class RedisConfig {


    @Bean
    public StringRedisSerializer stringRedisSerializer() {
        return new StringRedisSerializer();
    }

    @Bean
    public JdkSerializationRedisSerializer jdkSerializationRedisSerializer() {
        return new JdkSerializationRedisSerializer();
    }


    //用于序列化Long
    @Component
    public static class LongRedisSerializer implements RedisSerializer<Long> {

        @Override
        public byte[] serialize(Long o) throws SerializationException {
            long temp = o;
            byte[] b = new byte[8];
            for (int i = 0; i < b.length; i++) {
                b[i] = (byte) (temp & 0xff);
                temp = temp >> 8;
            }
            return b;
        }

        @Override
        public Long deserialize(byte[] b) throws SerializationException {
            long s = 0;
            for (int i = 0; i < 8; i++) {
                long v = b[i] & 0xff;
                v <<= (8 * i);
                s = s | v;
            }
            return s;

        }

    }


}
